package com.gamemost.templestay;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;

import com.gamemost.dao.BookDatasource;
import com.gamemost.entity.BookRecent;
import com.gamemost.entity.DownloadedBook;
import com.gamemost.layout.LayoutGridBook;
import com.gamemost.layout.LayoutMainScreen;
import com.gamemost.layout.LayoutMyLibrary;
import com.gamemost.layout.LayoutViewReadBook;
import com.gamemost.managers.LayoutManager;
import com.gamemost.managers.ResourcesManager;
import com.gamemost.templestay.R;

public class DownloadFileService extends AsyncTask<String, String, String> {
	ProgressDialog dialog;
	Activity activity;
	int lastest;
	File fileSql;
	public boolean isDownloadSuccess = false;
	private int typeBookDownload;
	private boolean isDownload = false;

	public DownloadFileService(Activity activity, int typeBookDownload) {
		// TODO Auto-generated constructor stub
		isDownloadSuccess = false;
		this.typeBookDownload = typeBookDownload;
		this.dialog = new ProgressDialog(activity);
		this.activity = activity;
		this.dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		this.dialog.setMessage(ResourcesManager.ac.m_load);
		this.dialog.setCancelable(false);
		if (!this.dialog.isShowing()) {
			this.dialog.show();
		}
	}

	@Override
	protected void onProgressUpdate(String... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
		this.dialog.setProgress(Integer.parseInt(values[0]));
	}

	DownloadedBook book;

	@Override
	protected String doInBackground(String... arg0) {
		// TODO Auto-generated method stub

		String title = arg0[0];
		String id = arg0[2]
				.replaceAll("[/\n\r\t\0\f`\\?\\*\\<>|\":\\.\\s]", "");
		System.out.println(title);
		File file = getOutputMediaFile(Config.EPUB_FILE, id + ".epub");
		if (arg0[1].contains("http:")) {
			isDownload = downloadFile(arg0[1], file);
			if (isDownload) {
				book = new DownloadedBook(arg0[2], title + ".epub", arg0[3],
						"", Integer.parseInt(arg0[6]));
				book.setTitle(title);

				book.setFilename(id + ".epub");
				book.setUrl(arg0[1]);
				book.setBookcover(arg0[3]);
				book.setCategoryId(arg0[4]);
				if (file.exists()) {
					BookDatasource.getInstance(activity.getBaseContext())
							.addBook(book);
					ResourcesManager.ac.listDownloadedBook.add(book);
					if (typeBookDownload == 1) {
						ResourcesManager.ac.listDownloadedBookInListBookStand
								.add(book);
					}					

				}
			}
		}

		return arg0[5];
	}

	@Override
	protected void onPostExecute(String id) {
		// TODO Auto-generated method stub
		this.dialog.dismiss();
		String idTmp;
		if (isDownload) {
			if (typeBookDownload == 0) {
				int startSwapIndex = ResourcesManager.ac.listDownloadedBook
						.size() - 1;
				int endSwapIndex = Integer.parseInt(id);
				System.out.println("qqqqqqqqqq id end swap "
						+ ResourcesManager.ac.listBookRecent.get(endSwapIndex)
								.getId());
				if (startSwapIndex < endSwapIndex) {
					swapBook(ResourcesManager.ac.listBookRecent,
							startSwapIndex, endSwapIndex);
					idTmp = ResourcesManager.ac.listBookRecent.get(
							startSwapIndex).getId();
					idTmp = idTmp.replaceAll(
							"[/\n\r\t\0\f`\\?\\*\\<>|\":\\.\\s]", "");
					ResourcesManager.ac.listBookRecent.get(startSwapIndex)
							.setFilename(idTmp + ".epub");
					System.out
							.println("pppp after "
									+ ResourcesManager.ac.listBookRecent.get(
											startSwapIndex).get(
											BookRecent.TAG_BOOK_ID));
					ResourcesManager.ac.listBookRecent.get(endSwapIndex)
							.setHasDownload(false);
					ResourcesManager.ac.listBookRecent.get(startSwapIndex)
							.setHasDownload(true);
					ResourcesManager.ac.listBookRecent.get(startSwapIndex)
							.setId(book.getId());
					book = ResourcesManager.ac.listBookRecent
							.get(startSwapIndex);
					System.out.println("ppppppp  title is " + idTmp);
				} else {
					idTmp = ResourcesManager.ac.listBookRecent
							.get(endSwapIndex).getId();
					idTmp = idTmp.replaceAll(
							"[/\n\r\t\0\f`\\?\\*\\<>|\":\\.\\s]", "");
					ResourcesManager.ac.listBookRecent.get(endSwapIndex)
							.setFilename(idTmp + ".epub");
					ResourcesManager.ac.listBookRecent.get(endSwapIndex)
							.setHasDownload(true);
					book = ResourcesManager.ac.listBookRecent.get(endSwapIndex);
				}

				LayoutMainScreen.getInstance().mAdapterNewBook
						.setListNewBook(ResourcesManager.ac.listBookRecent);
				LayoutMainScreen.getInstance().mAdapterNewBook
						.notifyDataSetChanged();
				this.dialog.dismiss();
				LayoutManager.getInstance().removeView(
						LayoutManager.getInstance().getCurrentView());
				LayoutViewReadBook.getInstance().setPreView(0);
				LayoutViewReadBook.getInstance().setCurrentBookReading(book);
				LayoutViewReadBook.getInstance().setNameBook(idTmp + ".epub");
				LayoutViewReadBook.getInstance().show();
				LayoutViewReadBook.getInstance().onLoadListener();
			} else if (typeBookDownload == 1) {
				int startSwapIndex = ResourcesManager.ac.listDownloadedBookInListBookStand
						.size() - 1;
				System.out.println(startSwapIndex + " start in dex ");
				int endSwapIndex = Integer.parseInt(id);
				System.out.println(endSwapIndex
						+ " end in dex "
						+ ResourcesManager.ac.listDownloadedBookInListBookStand
								.size());
				String title;
				if (startSwapIndex < endSwapIndex) {
					swapBook(ResourcesManager.ac.listBookInListBookStand,
							startSwapIndex, endSwapIndex);
					idTmp = ResourcesManager.ac.listBookInListBookStand.get(
							startSwapIndex).getId();
					idTmp = idTmp.replaceAll(
							"[/\n\r\t\0\f`\\?\\*\\<>|\":\\.\\s]", "");
					ResourcesManager.ac.listBookInListBookStand.get(
							startSwapIndex).setFilename(idTmp + ".epub");
					System.out
							.println("pppp after "
									+ ResourcesManager.ac.listBookInListBookStand
											.get(startSwapIndex).get(
													BookRecent.TAG_BOOK_ID));
					ResourcesManager.ac.listBookInListBookStand.get(
							endSwapIndex).setHasDownload(false);
					ResourcesManager.ac.listBookInListBookStand.get(
							startSwapIndex).setHasDownload(true);
					ResourcesManager.ac.listBookInListBookStand.get(
							startSwapIndex).setId(book.getId());
					System.out.println("ppppppp  title is " + idTmp);
				} else {
					idTmp = ResourcesManager.ac.listBookInListBookStand.get(
							endSwapIndex).getId();
					idTmp = idTmp.replaceAll(
							"[/\n\r\t\0\f`\\?\\*\\<>|\":\\.\\s]", "");
					ResourcesManager.ac.listBookInListBookStand.get(
							endSwapIndex).setFilename(idTmp + ".epub");
					ResourcesManager.ac.listBookInListBookStand.get(
							endSwapIndex).setHasDownload(true);
				}

				LayoutGridBook.getInstance().mAdapterBook
						.setListBookInBookStand(ResourcesManager.ac.listBookInListBookStand);
				LayoutGridBook.getInstance().mAdapterBook
						.notifyDataSetChanged();
				this.dialog.dismiss();
				LayoutManager.getInstance().removeView(
						LayoutManager.getInstance().getCurrentView());
				if (!LayoutViewReadBook.isLoading) {			
					LayoutViewReadBook.getInstance().setPreView(1);
					LayoutViewReadBook.getInstance()
							.setCurrentBookReading(book);
					LayoutViewReadBook.getInstance().setNameBook(
							idTmp + ".epub");
					LayoutViewReadBook.getInstance().show();
					LayoutViewReadBook.getInstance().onLoadListener();
					onchangeNewBoook();
				}
			} else if (typeBookDownload == 2) {
				onchangeNewBoook();
				int endSwapIndex = Integer.parseInt(id);
				idTmp = ResourcesManager.ac.getBookHasDownLoad()
						.get(endSwapIndex).getId();
				idTmp = idTmp.replaceAll("[/\n\r\t\0\f`\\?\\*\\<>|\":\\.\\s]",
						"");
				ResourcesManager.ac.getBookHasDownLoad().get(endSwapIndex)
						.setFilename(idTmp + ".epub");
				ResourcesManager.ac.getBookHasDownLoad().get(endSwapIndex)
						.setHasDownload(true);

				LayoutMyLibrary.getInstance().bookdownAdaprer
						.setListBookInBookStand(ResourcesManager.ac
								.getBookHasDownLoad());
				LayoutMyLibrary.getInstance().bookdownAdaprer
						.notifyDataSetChanged();
				this.dialog.dismiss();
				LayoutManager.getInstance().removeView(
						LayoutManager.getInstance().getCurrentView());
				if (!LayoutViewReadBook.isLoading) {
					LayoutViewReadBook.getInstance().setPreView(2);
					LayoutViewReadBook.getInstance()
							.setCurrentBookReading(book);
					LayoutViewReadBook.getInstance().setNameBook(
							idTmp + ".epub");
					LayoutViewReadBook.getInstance().show();
					LayoutViewReadBook.getInstance().onLoadListener();					
				}
			}
		}
		super.onPostExecute(id);
	}

	private void onchangeNewBoook() {
		// TODO Auto-generated method stub
		BookRecent br = new BookRecent();
		br.hasDownload = true;
		br.setFilename(book.getFilename());
		br.setId(book.getId());
		br.setImage(book.getImage());
		br.setTypeBook(book.getTypeBook());
		if (br.getTypeBook() == Config.FIX_LAYOUT) {
			br.setBookmark(book.getBookmarkString());
		} else {
			br.setBookmark(book.getStringBMReflow());
		}
		br.setBookcover(book.getBookcover());
		br.setTitle(book.getTitle());
		br.setUrl(book.getUrl());
		System.out.println("aaa");
		String imagePath = Environment.getExternalStorageDirectory().toString()
				+ Config.IMAGE_BOOK + "/" + br.getImage();
		File f = new File(imagePath);
		Bitmap bitmap = DownloadImageService.decodeFile(f);
		Bitmap bmp = Bitmap.createScaledBitmap(bitmap,
				2 * ResourcesManager.ac.width / 7,
				ResourcesManager.ac.height / 4, true);
		if (bitmap != null) {
			bmp = Bitmap.createScaledBitmap(bitmap,
					2 * ResourcesManager.ac.width / 7,
					ResourcesManager.ac.height / 4, true);
		} else {
			Drawable drawable = ResourcesManager.ac.getResources().getDrawable(
					R.drawable.no_book_cover);
			if (drawable instanceof BitmapDrawable) {
				book.setBitmap(Bitmap.createScaledBitmap(
						((BitmapDrawable) drawable).getBitmap(),
						2 * ResourcesManager.ac.width / 7,
						ResourcesManager.ac.height / 4, true));
			}
		}
		br.setBitmap(bmp);

		for (int i = 0; i < ResourcesManager.ac.listBookRecent.size(); i++) {
			if (ResourcesManager.ac.listBookRecent.get(i).getId()
					.equals(book.getId())) {
				System.out.println("11111111111111111");
				ResourcesManager.ac.listBookRecent.remove(i);
				break;
			}
		}
		ResourcesManager.ac.listBookRecent.add(br);
		if (ResourcesManager.ac
				.getPosMinNotBookDownload(ResourcesManager.ac.listBookRecent) != -1)
			Collections
					.swap(ResourcesManager.ac.listBookRecent,
							ResourcesManager.ac
									.getPosMinNotBookDownload(ResourcesManager.ac.listBookRecent),
							ResourcesManager.ac.listBookRecent.size() - 1);
		LayoutMainScreen.getInstance().mAdapterNewBook
				.setListNewBook(ResourcesManager.ac.listBookRecent);
		LayoutMainScreen.getInstance().mAdapterNewBook.notifyDataSetChanged();

	}

	public void swapBook(ArrayList<BookRecent> list, int startSwapIndex,
			int endSwapIndex) {
		Collections.swap(list, startSwapIndex, endSwapIndex);
	}

	public File getOutputMediaFile(String path, String name) {
		File mediaStorageDir = new File(
				Environment.getExternalStorageDirectory(), path);
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				return null;
			}
		}
		File mediaFile;
		mediaFile = new File(mediaStorageDir.getPath() + File.separator + name);
		return mediaFile;
	}

	private boolean downloadFile(String url, File outputFile) {
		try {
			URL u = new URL(url);
			URLConnection conn = u.openConnection();
			int lenghtOfFile = conn.getContentLength();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			DataOutputStream fos = new DataOutputStream(new FileOutputStream(
					outputFile));
			byte data[] = new byte[1024];
			long total = 0;
			int count;
			while ((count = bis.read(data)) != -1) {
				total += count;
				publishProgress("" + (int) ((total * 100) / lenghtOfFile));
				fos.write(data, 0, count);
			}
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		return true;
	}

}
